package com.max.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Component
//@ConfigurationProperties(prefix = "token")
public class JwtUtils {

    //私钥
    @Value("${token.secret}")
    private String secret;

    //过期时间(s)
    @Value("${token.expireTime}")
    private Long expireTime;


    /**
     * 创建JWT
     *
     * @param claims  载荷
     * @param subject 主题信息
     * @return 返回token
     */
    public String createJWTToken(Map<String, Object> claims, String subject) {
        long nowMillis = System.currentTimeMillis();
        return Jwts.builder()
                .addClaims(claims)
                .setSubject(subject)
                .setIssuedAt(new Date(nowMillis))
                .setExpiration(new Date(nowMillis + expireTime * 1000))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }


    /**
     * 验证JWT
     *
     * @param jwtToken token
     * @param username 主体用户
     * @return 返回是否校验成功
     */
    public boolean verifyJWTToken(String jwtToken, String username) {
        Jws<Claims> claimsJws = parseJWTToken(jwtToken);
        return username.equals(claimsJws.getBody().getSubject());
    }


    /**
     * 解析JWT
     *
     * @param jwt token
     * @return 返回解析结果
     */
    public Jws<Claims> parseJWTToken(String jwt) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(jwt);
    }

}
